/**
 * tarside-ftp -- A simple FTP client, using the ANSI C and GTK+.
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "stor.h"
#include "login.h"
static void send_file(char* path, int df_connect) {
	FILE *stream = fopen(path, "rb");
	if (stream == NULL)
		perror("Error opening file");
	else {
		fseek(stream, 0, SEEK_SET);
		char line[256];
		while (NULL != fgets(line, 256, stream)) {
			send(df_connect, line, strlen(line), 0);
		}
		fclose(stream);
	}
}

static void port_stor_data_info(int port, char *path[]) {
	char message[256] = { '\0' };
	int bind_socket = open_bind(port);
	int address_length = sizeof(struct sockaddr_in);
	struct sockaddr_in address_client;
	int df_connect;
	sprintf(message, "accept socket %i port %i \n", bind_socket, port);
	set_commond_info(message);
	if ((df_connect = accept(bind_socket, (struct sockaddr*) &address_client, &address_length)) == -1) {
		perror("accept() error\n");
		exit(1);
	}
	sprintf(message,"You got a connection from %s\n", inet_ntoa(address_client.sin_addr));
	set_commond_info(message);
	send_file(path, df_connect);
	close(df_connect);
	close(bind_socket);
	sprintf(message, "close connect %i \n", bind_socket);
	set_commond_info(message);
	printf(message, "close connect %i \n", bind_socket);
	set_commond_info(message);
}

static void pasv_stor_data_info(int socket_connect, int port, char path[]) {
	int new_fd = create_connect(get_remote_ip(socket_connect), port);
	send_file(path, new_fd);
	close(new_fd);
}

void stor_comment(int socket_connect, char put[], char path[]) {
	if (get_ftp_model()) {
		char ports[256] = { '\0' };
		create_port_comment(&ports);
		send_cmd(socket_connect, ports);
		send_cmd(socket_connect, put);
		port_stor_data_info(get_port(), path);
	} else {
		char pasv[256] = "PASV \r\n";
		send_cmd(socket_connect, pasv);
		char buffer[1024];
		recv_cmd(socket_connect, buffer, 1024);
		printf("PASV : %s", buffer);
		send_cmd(socket_connect, put);
		int port = get_pasv_port(buffer);
		pasv_stor_data_info(socket_connect, port, path);
	}
	char buffer[1024] = { '\0' };
	recv_result(socket_connect, "226", buffer);
	printf("commond result : %s", buffer);
}
